from typing import Optional, Tuple

from rest_framework.request import Request
from rest_framework_simplejwt.authentication import JWTAuthentication, AuthUser
from rest_framework_simplejwt.exceptions import InvalidToken
from rest_framework_simplejwt.tokens import Token

from extensions.exceptions import NotAuthenticated
from apps.system.models import User


# class BaseAuthentication(JWTAuthentication):
#
#     def authenticate(self, request):
#         if (header := self.get_header(request)) is None:
#             return None
#
#         if (raw_token := self.get_raw_token(header)) is None:
#             return None
#
#         try:
#             validated_token = self.get_validated_token(raw_token)
#             user = User.objects.get(id=validated_token['user_id'])
#         except (KeyError, InvalidToken, User.DoesNotExist):
#             return None
#
#         return user, validated_token
#
#
# __all__ = [
#     'BaseAuthentication',
# ]


"""
进行token校验

"""
# JWTAuthentication类
class BaseAuthentication(JWTAuthentication):
    # 重写authenticate方法
    def authenticate(self, request):
        # 从request中获取header信息，如果为空，则返回None
        if (header := self.get_header(request)) is None:
            return None
        # 从header中获取token  如果为空，则返回None
        if (raw_token := self.get_raw_token(header)) is None:
            return None
        try:
            # 进行token 校验
            validated_token = self.get_validated_token(raw_token)
            # 从token中获取到user_id，通过id进行查询user对象
            user = User.objects.get(id=validated_token['user_id'])
            # 异常处理
        except (KeyError, InvalidToken, User.DoesNotExist):
            return None
        # 最后返回token和user
        return validated_token, user


# __all__是python模块中的一个特殊变量，其中用来表示该模块被别的模块使用的时候，只有写在里面的类才可以被使用
__all__ = [
    'BaseAuthentication'
]
